package com.moleq.util;

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

public class EditTextMaxLengthWatcher implements TextWatcher {
	
	private int maxLen;
	
	private EditText editText;
	
	private Context context;
	
	public EditTextMaxLengthWatcher(int maxLen,EditText editText,Context context){
		this.maxLen = maxLen;
		this.editText = editText;
		this.context = context;
	}
	
	
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
		if(ChangeMode.mode == 0){
			return;
		}
	
		editText.setTag(1);
		
		Editable editable = editText.getText();
		int len = editable.length();
		
		
		
		if(len > maxLen){
			int selEndIndex = Selection.getSelectionEnd(editable);
			String str = editable.toString();
			
			String newStr = str.substring(0,maxLen);
			editText.setText(newStr);
			editable =editText.getText();
			
			int newLen = editable.length();
			
			if(selEndIndex > newLen){
				selEndIndex = editable.length();
			}
			
			Selection.setSelection(editable, selEndIndex);
		}
	}
	
	
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
	}

	
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}

}
